import json
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from .models import Permissions
from django_redis import get_redis_connection

from utils.custom_log   import log_start
logger = log_start('signals')



@receiver(pre_delete, sender=Permissions)
def delete_permissions_from_redis(sender, instance, **kwargs):
    """
    Permissions模型,删除前更新redis
    :param sender:
    :param instance:
    :param kwargs:
    :return:
    """
    
    conn = get_redis_connection('user_info')
    if conn.hexists('user_permissions_manage', instance.path):
        conn.hdel('user_permissions_manage', instance.path)

    info = '触发信号... delete_permissions_from_redis instance_path: %s' % instance.path
    logger.info(info)


@receiver(post_save, sender=Permissions)
def save_permissions_to_redis(sender, instance, **kwargs):
    """
    Permissions模型,保存后更新redis
    :param sender:
    :param instance:
    :param kwargs:
    :return:
    """
    conn = get_redis_connection('user_info')

    if not instance.menu and kwargs.get('created')  :
        if  conn.hexists('user_permissions_manage', instance.path):
            permissions = json.loads(conn.hget('user_permissions_manage', instance.path))
            permissions.append({
                'method': instance.method,
                'sign': instance.sign,
                'id': instance.id,
            })
            conn.hset('user_permissions_manage', instance.path, json.dumps(permissions))
        else:
            conn.hset('user_permissions_manage', instance.path, json.dumps([{
                'method': instance.method,
                'sign': instance.sign,
                'id': instance.id,
            }]))

        info = '触发信号... create_permissions_to_redis'
        logger.info(info)

    else:
        if not instance.menu:
            
            # 接口权限,判断权限path的变化,更新redis
            try:
                permission = Permissions.objects.get(id=instance.id)
            except Permissions.DoesNotExist:
                return

            if conn.hexists('user_permissions_manage', permission.path):
                cache_permissions = json.loads(conn.hget('user_permissions_manage', permission.path))
                for index, value in enumerate(cache_permissions):
                    if value.get('id') == instance.id:
                        del cache_permissions[index]  # 清空原缓存数据
                cache_permissions.append({
                        'method': instance.method,
                        'sign': instance.sign,
                        'id': instance.id,
                    })
                conn.hset('user_permissions_manage', instance.path, json.dumps(cache_permissions))
            else:
                pass

        info = '触发信号... update_permissions_to_redis instance_id: %s' % instance.id
        logger.info(info)